#filepath:/Users/someone/proj01/五子棋.py
import tkinter as tk
from tkinter import messagebox

class Gobang:
    def __init__(self):
        self.window = tk.Tk()
        self.window.title("五子棋")
        self.canvas = tk.Canvas(self.window, width=650, height=650, bg='#DEB887') # 棋盘背景色
        self.canvas.pack()
        
        self.board = [[0]*15 for _ in range(15)]  # 15x15棋盘
        self.current_player = 1  # 1:黑棋 2:白棋
        self.game_over = False
        
        self.draw_board()  # 绘制棋盘
        self.canvas.bind("<Button-1>", self.click_handler)  # 绑定鼠标点击事件

    # 绘制棋盘  
    def draw_board(self):
        # 绘制棋盘线
        for i in range(15):
            self.canvas.create_line(40, 40+i*40, 600, 40+i*40) # 横线
            self.canvas.create_line(40+i*40, 40, 40+i*40, 600) # 竖线

    # 鼠标点击事件处理函数   
    def click_handler(self, event):
        if self.game_over:
            return
            
        x, y = (event.x-20)//40, (event.y-20)//40
        if 0 <= x < 15 and 0 <= y < 15 and self.board[x][y] == 0:
            self.board[x][y] = self.current_player
            self.draw_piece(x, y)
            if self.check_win(x, y):
                self.show_winner()
                self.game_over = True
            else:
                self.current_player = 2 if self.current_player == 1 else 1

    # 绘制棋子
    def draw_piece(self, x, y):
        color = 'black' if self.current_player == 1 else 'white'
        self.canvas.create_oval(
            40*x + 20, 40*y + 20,
            40*x + 60, 40*y + 60,
            fill=color, outline='black'
        )

    def check_win(self, x, y):
        directions = [(1,0), (0,1), (1,1), (1,-1)]
        for dx, dy in directions:
            count = 1
            # 正向检查
            i, j = x+dx, y+dy
            while 0 <= i <15 and 0 <= j <15 and self.board[i][j] == self.current_player:
                count +=1
                i += dx
                j += dy
            # 反向检查
            i, j = x-dx, y-dy
            while 0 <= i <15 and 0 <= j <15 and self.board[i][j] == self.current_player:
                count +=1
                i -= dx
                j -= dy
            if count >=5:
                return True
        return False

    def show_winner(self):
        winner = "黑方" if self.current_player ==1 else "白方"
        messagebox.showinfo("游戏结束", f"{winner}获胜！")

    def run(self):
        self.window.mainloop()

if __name__ == "__main__":
    game = Gobang()
    game.run()
